import { Component, OnInit, Inject } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import * as dtos from './services/todo.model';
import { TodoService } from './services/todo.service';
import { UUID } from 'angular2-uuid';
import { Observable, Subscription } from 'rxjs/Rx';

@Component({
    selector: 'app-todo',
    templateUrl: './todo.component.html',
    styleUrls: ['./todo.component.css']
})
export class TodoComponent implements OnInit {
    todos: dtos.Todo[] = [];
    desc = '';
    constructor(
              @Inject('todoService') private _service: TodoService,
              private route: ActivatedRoute,
              private router: Router
              ) { 

    }

    ngOnInit() {

      this.route.params.forEach((value)=>{
        let filter = value['filter'];
        this.filterTodos(filter);
      });
    }
    filterTodos(filter: string){
      this._service.getFilterTodo(filter)
        .subscribe(value=>{
          this.todos = [...value];
        });
    }
    addTodo(){
      let todo = new dtos.Todo();
      todo = {Id: 0, Guid: UUID.UUID(), Desc: this.desc, Completed: false};
      this._service.postTodo(todo)
        .subscribe(value=>{
          todo.Id = value;
          this.todos = [...this.todos, todo];
          this.desc='';
        }, error=>{
          alert("通讯出错了");
        });
    }
    getTodos(): void{
      this._service.getTodo().subscribe(value=>{
        this.todos = [...value];
      },error=>{

      });
    }
    toggleTodo(todo: dtos.Todo){
      const i = this.todos.indexOf(todo);
      todo.Completed = !todo.Completed;
      this._service.postTodo(todo)
        .subscribe(value=>{
          this.todos = [...this.todos.slice(0, i), todo, ...this.todos.slice(i+1)];
        });
    }
    removeTodo(todo: dtos.Todo){
      const i = this.todos.indexOf(todo);
      this._service.deleteTodoById(todo.Id)
        .subscribe(value=>{
          this.todos = [...this.todos.slice(0, i), ...this.todos.slice(i+1)];
        });
    }
    onTextChanges(input: string){
      this.desc = input;
      console.log(input);
    }
    toggleAll(){
      this.todos.forEach(todo=> this.toggleTodo(todo));
    }
    clearCompleted(){
      this.todos.forEach(todo=>{
        if(todo.Completed == true){
          this.removeTodo(todo);
        }
      });
    }
}
